<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>GoodsManger</title>
    <link href="css/base.css" type="text/css" rel="stylesheet">
    <link href="css/tab.css" type="text/css" rel="stylesheet">
    <link href="css/item.css" type="text/css" rel="stylesheet">
    <link href="css/item_do.css" type="text/css" rel="stylesheet">
    <link rel="stylesheet" type="text/css"
          href="plugin/jquery-easyui-1.3.3/themes/ui-sunny/easyui.css">
    <link rel="stylesheet" type="text/css"
          href="plugin/jquery-easyui-1.3.3/themes/icon.css">
    <script type="text/javascript"
            src="plugin/jquery-easyui-1.3.3/jquery.min.js"></script>
    <script type="text/javascript"
            src="plugin/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
    <script type="text/javascript"
            src="plugin/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
    <link rel="stylesheet" href="plugin/kindeditor/themes/default/default.css"/>
    <script charset="utf-8" src="plugin/kindeditor/kindeditor-all.js"></script>
    <script charset="utf-8" src="plugin/kindeditor/lang/zh_CN.js"></script>
    <script charset="utf-8" src="plugin/ajaxfileupload.js"></script>
</head>
<body style="margin:1px;margin-top: 3px;" id="ff">
<table id="dg"  class="easyui-datagrid" pagination="true" data-options="pageSize:4,pageList:[4,8,12]"
       rownumbers="true" fit="true"
       url="/goods/search"
       toolbar="#tb">
    <thead data-options="frozen:true">
    <tr>
        <th field="cb" checkbox="true" align="center"></th>
        <th field="id" width="10%" align="center" hidden="true">编号</th>
        <th field="goodsname" width="100%" align="center">名称</th>
        <th field="typename" width="100%" align="center" formatter="getTypename">商品类别</th>
        <th field="img1" width="150%" align="center" formatter="formatProPic">缩略图</th>
        <th field="price" width="100%" align="center">价格</th>
        <th field="inventory" width="100%" align="center">库存</th>
        <th field="createTime" width="150%" align="center">创建时间</th>
        <th field="status" width="100%" align="center" formatter="getStatus">状态</th>
        <th field="content" width="100%" align="center"
            formatter="formatHref">操作
        </th>
    </tr>
    </thead>
</table>
<div id="tb">

    <div>
        &nbsp;<span style="font-size: 15px;">名称：&nbsp;</span><input style="height: 20px;font-size: 15px" type="text" id="goodsname" size="20"
                              onkeydown="if(event.keyCode==13) searchGoods()"/>&nbsp; <a
            href="javascript:searchGoods()" class="easyui-linkbutton"
            iconCls="icon-search" plain="true">搜索</a>
    </div>
    <div style="margin-top: 10px;">
        <a href="javascript:openAddDialog()" class="easyui-linkbutton"
           iconCls="icon-add" plain="false">新增</a>
        <a href="javascript:openEditDialog()" class="easyui-linkbutton"
           iconCls="icon-edit" plain="false">编辑</a>
        <a  href="javascript:deleteGoods()" class="easyui-linkbutton"
           iconCls="icon-remove" plain="false">删除</a>
        <a
           href="javascript:agreeGood()"
           class="easyui-linkbutton" iconCls="icon-ok" >上架</a> 
        <a href="javascript:refuseGood()" class="easyui-linkbutton"
           iconCls="icon-cancel" plain="false">下架</a>
    </div>
    
</div>
<div id="dlg" class="easyui-dialog"
     style="width: 1000px;height:550px;padding: 10px 20px; position: relative; z-index:1000;"
     closed="true" buttons="#dlg-buttons">
    <form id="fm" method="post">
        <table cellspacing="8px">
            <tr>
                <td>名称：</td>
                <td><input type="text" id="goodname" name="goodsname"
                           class="easyui-validatebox" required="true"/>&nbsp;<font
                        color="red">*</font>
                    <input id="goodsIdfm" name="id" type="hidden" value="0">
                </td>
            </tr>
            <tr>
                <td>类别：</td>
                <td>
                    <select id="goodtype" name="typeid"></select>
                </td>
            </tr>
            <tr>
                <td>价格：</td>
                <td>
                    <input type="number" id="price" name="price"
                           class="easyui-validatebox" required="true" min="0"/>&nbsp;<font
                        color="red">*</font>
                </td>
            </tr>
            <tr>
                <td>库存：</td>
                <td>
                    <input type="text" id="inventory" name="inventory"
                           class="easyui-validatebox" required="true" onkeyup="carNum($(this))"/>&nbsp;<font
                        color="red">*</font>
                </td>
            </tr>
            <tr>
                <td>图片：</td>
                <td>
                    <input id="image" type="button" value="选择图片">&nbsp;
                    <font id="imageTip" color="red">*商品图片最多3张</font>
                </td>
            </tr>
            <tr id="pictr">
            </tr>
            <tr>
                <td>详细内容</td>
                <td>
                    <textarea id="editor"
                              style="width:800px;height:400px;visibility:hidden;"></textarea>
                </td>
            </tr>
        </table>
    </form>
</div>

<div id="dlg-buttons">
    <a href="javascript:saveGoods()" class="easyui-linkbutton"
       iconCls="icon-ok">保存</a> <a href="javascript:closePictureDialog()"
                                   class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>

</body>
<script type="text/javascript">
    var url = "/goods/insert";
    
    $(function () {
        //富文本编辑器
        KindEditor.ready(function (K) {
        	/*富文本编辑器   start*/
            this.editor
                = K.create('textarea[id="editor"]', {
                items: ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
                    'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'multiimage',
                    'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
                    'anchor', 'link', 'unlink'],
                uploadJson: '/upload/picture',
                filePostName: 'file',
                fileManagerJson: '/images',
                allowFileManager: true
            });
            /*富文本编辑器   end*/
            
            
            /*单独调用kindEditor图片上传   start*/
            picEditor= K.editor({
                allowFileManager : true,//允许图片管理 开启后再挑选图片的时候可以直接从图片空间内挑选
                allowImageUpload: true,
                uploadJson: '/upload/picture',
                filePostName: 'file',
                imageUploadLimit : 3,
                imageSizeLimit:'5MB'
            });
            //给按钮添加click事件
            K('#image').click(function() {
            	picEditor.loadPlugin('multiimage', function() {
                    //图片弹窗的基本参数配置
                    picEditor.plugin.multiImageDialog({
                        //点击弹窗内”确定“按钮所执行的逻辑
                        clickFn : function(result) {
                        	//清空预览和图偏url隐藏域
                        	$("#pictr").children().remove();
                        	
                        	if(result.length>0){
                        		$("#pictr").append(`<td>图片预览：</td>`);
                        	}
                        	
                        	//循环赋值
                        	for(let i=0;i<result.length;i++){
                        		$("#pictr").append(`<td>
                        				<img style="width:80px;height:80px" src="${result[i].data}"/>
                                        <input id="img${i+1}" type="hidden" value="${result[i].data}">
                                        </td>`);
                        	}
                        	//更改提示
                        	$("#imageTip").text(`已上传数量：${result.length}`);
                        	//隐藏弹窗
                            picEditor.hideDialog(); 
                        }
                    });
              });
            }); 
            /*单独调用kindEditor图片上传   end*/
           
        });
    });

    /*弹窗-----新增*/
    function openAddDialog() {
        $("#dlg").dialog("open").dialog("setTitle", "添加特产信息");
        editor.html('请输入特产详情');
        //请求所有的商品类别
        $.ajax({
            url:"/goodstype/allChildType",
            type:"GET",
            async : false,
            dataType: "json",
            success:function(result){
                 for(var i=0;i<result.data.length;i++){
                     $("#goodtype").append(`<option value="${result.data[i].id}">${result.data[i].typename}</option>`);
                 }
            }
        })
    }
    
    /*弹窗-----编辑*/
    function openEditDialog(){
    	var selectedRows = $("#dg").datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要编辑的数据！");
            return;
        }
        var row = selectedRows[0];
        $("#dlg").dialog("open").dialog("setTitle", "编辑特产");
        $('#fm').form('load', row);
        editor.html(row.details);
        
        //图片组件赋值
        if(row.img1!=null){
        	$("#pictr").append(`
                    <td>
                        <img style="width:80px;height:80px" src="${row.img1}"/>
                        <input id="img1" type="hidden" value="${row.img1}">
                    </td>`);
        }
        if(row.img2!=null){
            $("#pictr").append(`
                    <td>
                        <img style="width:80px;height:80px" src="${row.img2}"/>
                        <input id="img2" type="hidden" value="${row.img2}">
                    </td>`);
        }
        if(row.img3!=null){
            $("#pictr").append(`
                    <td>
                        <img style="width:80px;height:80px" src="${row.img3}"/>
                        <input id="img3" type="hidden" value="${row.img3}">
                    </td>`);
        }
        
       //请求所有的商品类别
        $.ajax({
            url:"/goodstype/allChildType",
            type:"GET",
            async : false,
            dataType: "json",
            success:function(result){
                 for(var i=0;i<result.data.length;i++){
                	 if(row.typeid==result.data[i].id){
                		$("#goodtype").append(`<option value="${result.data[i].id}" selected="selected">${result.data[i].typename}</option>`);
                	 }else{
                        $("#goodtype").append(`<option value="${result.data[i].id}">${result.data[i].typename}</option>`);
                	 }
                 }
            }
        });
        
        url="/goods/update";
    }
    
    
    /*保存*/
    function saveGoods(){
    	var id=$("#goodsIdfm").val();
    	var goodsname=$("#goodname").val();
    	var typeid=$("#goodtype").val();
    	var price=$("#price").val();
    	var img1=$("#img1").val();
    	var img2=$("#img2").val();
    	var img3=$("#img3").val();
    	var details=editor.html();
    	var inventory=$("#inventory").val();
    	var data={"id":id,"goodsname":goodsname,"typeid":typeid,"price":price,"inventory":inventory,
    		     "img1":img1,"img2":img2,"img3":img3,"details":details};
    	
    	$.ajax({
            type: "post",
            dataType: "json",
            url: url,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            success: function (result) {
                console.log(result);//打印服务端返回的数据
                if (result.resultCode == 200) {
                    $.messager.alert("系统提示", "保存成功");
                    $("#dlg").dialog("close");
                    $("#dg").datagrid("reload");
                    resetValue();
                }
                else {
                    $.messager.alert("系统提示", "操作失败");
                    $("#dlg").dialog("close");
                    resetValue();
                }
                ;
            },
            error: function () {
                $.messager.alert("系统提示", "操作失败");
                resetValue();
            }
        });
    }
    
    /*搜索*/
    function searchGoods() {
        $("#dg").datagrid('load', {
            "goodsname": $("#goodsname").val(),
        });
    }

    /*删除*/
    function deleteGoods() {
        var selectedRows = $("#dg").datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要删除的数据！");
            return;
        }
        var strIds = [];
        for (var i = 0; i < selectedRows.length; i++) {
            strIds.push(selectedRows[i].id);
        }
        var ids = strIds.join(",");
        $.messager.confirm("系统提示", "您确认要删除这<font color=red>"
                + selectedRows.length + "</font>条数据吗？", function (r) {
            if (r) {
                $.ajax({
                    type: "GET",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: "/goods/delete/" + ids,//url
                    data: {},
                    success: function (result) {
                        console.log(result);//打印服务端返回的数据
                        if (result.resultCode == 200) {
                            $.messager.alert(
                                    "系统提示",
                                    "数据已成功删除！");
                            $("#dg").datagrid(
                                    "reload");
                        }
                        else {
                            $.messager.alert(
                                    "系统提示",
                                    "数据删除失败！");
                        }
                    },
                    error: function () {
                        $.messager.alert("ERROR！");
                    }
                });
            }
        });
    }
   
    /*下架*/
    function refuseGood(){
    	var selectedRows = $("#dg").datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要下架的商品！");
            return;
        }
    	var id=selectedRows[0].id;//商品id
    	var status=selectedRows[0].status;
    	if(status==0){
    		$.messager.alert("系统提示", "选择的商品已是下架状态！");
    		return;
    	}
    	
    	var dt={"id":id,"status":0};
    	$.messager.confirm("系统提示", "您确认要下架？", function (r) {
            if (r) {
                $.ajax({
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: "/goods/update",//url
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(dt),
                    success: function (result) {
                        console.log(result);//打印服务端返回的数据
                        if (result.resultCode == 200) {
                            $("#dg").datagrid("reload");
                        }
                        else {
                            $.messager.alert(
                                    "系统提示",
                                    "驳回失败！");
                        }
                    },
                    error: function () {
                        $.messager.alert("ERROR！");
                    }
                });
            }
        });
    }

    /*上架*/
    function agreeGood(){
    	var selectedRows = $("#dg").datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要上架的商品！");
            return;
        }
        var id=selectedRows[0].id;//商品id
        var status=selectedRows[0].status;
        if(status==1){
            $.messager.alert("系统提示", "选择的商品已是上架状态！");
            return;
        }
        var dt={"id":id,"status":1};
        $.messager.confirm("系统提示", "您确认要上架？", function (r) {
            if (r) {
                $.ajax({
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: "/goods/update",//url
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(dt),
                    success: function (result) {
                        console.log(result);//打印服务端返回的数据
                        if (result.resultCode == 200) {
                            $("#dg").datagrid("reload");
                        }
                        else {
                            $.messager.alert(
                                    "系统提示",
                                    "上架失败！");
                        }
                    },
                    error: function () {
                        $.messager.alert("ERROR！");
                    }
                });
            }
        });
    }

    /*图片预览*/
    function formatProPic(val, row) {
        return "<img width=100 height=100 src='" + val + "'>";
    }
    
    /*类型查询*/
    function getTypename(val,row){
    	var typename="";
        $.ajax({
            url:"/goodstype/info/"+row.typeid,
            type:"GET",
            async : false,
            dataType: "json",
            success:function(result){
                 if(result.resultCode==200){
                	 typename=result.data.typename;
                 }
            }
        })
        return '<span>'+typename+'</span>';
    }
    
    /*状态*/
    function getStatus(val,row){
    	if(val==null){
    		var html1=`<span style="color: blue;">下架中</span>`;
            return html1;
    	}
    	
    	if(val==0){
           var html1=`<span style="color: blue;">下架中</span>`;
           return html1;
        }
    	
    	if(val==1){
    		var html2=`<span style="color: green;">上架</span>`;
    		return html2;
    	}
    }
    
    /*查看详情*/
    function formatHref(val, row) {
        var a= `<a style="color:blue" href="Goodsdetail.html?id=${row.id}" target='_blank'>查看详情</a></br>`;
        return a;
    }

    /*重置弹窗*/
    function resetValue() {
    	$('#fm')[0].reset();
    	$("#pictr").children().remove();
    	$("#goodtype").children().remove();
    }

    function closePictureDialog() {
        $("#dlg").dialog("close");
        resetValue();
    }
    function carNum($this){
        //输入框的值
        var value = $this.val() ;
        
        if(isNaN(value)){//判断值是不是数字
            $this.val(1) ;
        }else if(value==""){//这是当只有1位的时候，删除这个会进入这个判断，如果没有该判断，当只有一位的时候就不能删除
            
        }else if(value==0){//判断值是不是1
            $this.val(1) ;
        }else if(value.indexOf(".")!=-1){//判断有没有输入小数点
            $this.val(value.substring(0,value.indexOf(".")))
        }
    }
</script>
</head>

</html>